package ru.ssau.customerManagement.controller.threads.client;

import ru.ssau.customerManagement.controller.remoting.OperationRequest;
import ru.ssau.customerManagement.controller.remoting.OperationResponse;
import ru.ssau.customerManagement.controller.remoting.RequestExecutor;
import ru.ssau.customerManagement.controller.remoting.notifications.ClientSideNotificationController;
import ru.ssau.customerManagement.model.entities.Customer;
import ru.ssau.customerManagement.model.entities.CustomerLocation;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;
import java.io.*;
import java.lang.reflect.InvocationTargetException;
import java.net.Socket;

/**
 * Created by illabefat on 27.11.14.
 */
public class NotificationsListener implements Runnable{
    private final Socket socketToListen;
    private final ClientSideNotificationController notificationController;
    private final RequestExecutor requestExecutor;

    public NotificationsListener(Socket socketToListen, ClientSideNotificationController notificationController) {
        this.socketToListen = socketToListen;
        this.notificationController = notificationController;
        requestExecutor = new RequestExecutor(this.notificationController);
    }

    @Override
    public void run() {
        try {
            ObjectOutputStream out = new ObjectOutputStream(socketToListen.getOutputStream());
            ObjectInputStream in = new ObjectInputStream(socketToListen.getInputStream());
            while (true)
            {
                JAXBContext jaxbContext1 = JAXBContext.newInstance(OperationResponse.class, OperationRequest.class,
                        Customer.class, CustomerLocation.class);
                Marshaller jaxbMarshaller = jaxbContext1.createMarshaller();
                Unmarshaller jaxbUnmarshaller = jaxbContext1.createUnmarshaller();

                String xmlRequest = in.readUTF();
                OperationRequest request = (OperationRequest) jaxbUnmarshaller.unmarshal(new StringReader(xmlRequest));
                OperationResponse response = requestExecutor.executeRequest(request);

                StringWriter sw = new StringWriter();
                jaxbMarshaller.marshal(response, sw);
                String xmlString = sw.toString();

                out.writeUTF(xmlString);
                out.flush();
                out.reset();
            }
        } catch (IOException e) {
            e.printStackTrace();
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (JAXBException e) {
            e.printStackTrace();
        }
    }
}
